package com.example.apricots;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentManager;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.apricots.Activity.FaceAttrVideoPreviewActivity;
import com.example.apricots.Adapter.MyMenuAdapter;
import com.example.apricots.Common.GlobalConfig;
import com.example.apricots.Common.IFragment;
import com.example.apricots.Common.Utils;
import com.example.apricots.Fragment.FragmentFour;
import com.example.apricots.Fragment.FragmentSetting;
import com.example.apricots.Fragment.FragmentThree;
import com.example.apricots.Fragment.FragmentTwo;
import com.example.apricots.Fragment.Fragmentone;
import com.example.apricots.Services.BGMusicService;
import com.example.apricots.Services.CameraPreview;
import com.example.apricots.Services.SavePictureTask;
import com.example.apricots.Utils.ArcFaceUtil;
import com.example.apricots.bean.MenuListBean;
import com.example.apricots.Utils.Biometric;
import com.example.apricots.Utils.MenuTitleBar;
import com.example.apricots.Utils.MobileDetail;
import com.example.apricots.bean.User;
import com.example.apricots.observer.ICaptureTakenEvent;
import com.example.apricots.observer.VolumeChangedObserver;
import com.jpeng.jpspringmenu.MenuListener;
import com.jpeng.jpspringmenu.SpringMenu;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.Executor;

import cn.onestravel.navigation.view.BottomNavigationBar;

public class MainActivity extends AppCompatActivity implements MenuListener, ICaptureTakenEvent, IFragment {

    /**
     * 请求选择本地图片文件的请求码
     */
    private static final int ACTION_CHOOSE_IMAGE = 0x201;
    private Bitmap mBitmap = null;
    //静拍相关
    Camera _camera;
    CameraPreview _cameraPreview;
    boolean _isReadToGo = false;
    int _front_camera_index = -1;
    int _back_camera_index = -1;
    int _currentCameraIndex = -1;
    VolumeChangedObserver _volumeChanged;
    FrameLayout _previewContainer;
    ObjectAnimator _colorAnimation;


    private static final String TAG = MainActivity.class.getSimpleName();
    SpringMenu mSpringMenu;
    MenuTitleBar mTitleBar;
    WebView wv_reusme;
    ConstraintLayout constraint_parent;
    ImageView img_icon;
    private BottomNavigationBar bottomView;
    private FrameLayout mainFragment;
    FragmentManager fragmentManager;
    User user;
    Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            new SavePictureTask(new SavePictureTask.SavePicListener() {
                @Override
                public void saveFinish() {
                    //这句是最重要的,必须执行startPreview后,才能再次拍照
                    _camera.startPreview();
                    Log.e(TAG, "saveFinish: 相机预览完成");
                    _isReadToGo = true;
                }
            }).execute(data);
        }
    };


    private Handler handler = new Handler();

    private Executor executor = new Executor() {
        @Override
        public void execute(Runnable command) {
            handler.post(command);
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        GlobalConfig.RawImageStoreUrl = Utils.getWritePath(this) + "/imgs/";
        _volumeChanged = new VolumeChangedObserver(new Handler(), this);
        user = (User) getIntent().getSerializableExtra("user");
        initview();
        MobileDetail.getInstance().setScreenLight(this);
        /*Log.e(TAG, "getinfo=: " + MobileDetail.getInstance().getInfo(this)
                + "\ngetHeightAndWidth=:" + MobileDetail.getInstance().getHeightAndWidth(this)[0] + "\t" + MobileDetail.getInstance().getHeightAndWidth(this)[1]
                + "getCpuInfo=:" + MobileDetail.getInstance().getCpuInfo()
                + "isroot=:" + MobileDetail.getInstance().isRoot()
                + "getTotalMemory=:" + MobileDetail.getInstance().getTotalMemory(this));*/

        initMenu();
        initBiometric();//检测手机是否可以生物识别
        initCamera();

    }

    private void initCamera() {
        int cameraCount = Camera.getNumberOfCameras();
        Camera.CameraInfo cameraInfo = new Camera.CameraInfo();

        for (int i = 0; i < cameraCount; i++) {
            Camera.getCameraInfo(i, cameraInfo);
            if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK)
                _back_camera_index = i;
            else if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
                _front_camera_index = i;
        }
        _currentCameraIndex = _back_camera_index;
    }


    private void initBiometric() {
        Biometric biometric = new Biometric();
        biometric.detecBiometric(MainActivity.this);
    }


    private void initview() {
        wv_reusme = findViewById(R.id.wv_resume);
        constraint_parent = findViewById(R.id.constraint_parent);
        _previewContainer = findViewById(R.id.flCameraContainer);

        /*vp_fragment=findViewById(R.id.vp_fragment);
        List<Fragment> fragments=new ArrayList<>();
        fragments.add(new Fragmentone());
        fragments.add(new Fragmentone());
        fragments.add(new Fragmentone());
        fragments.add(new Fragmentone());
        fragments.add(new FragmentSetting());
        FragmentAdapter adapter=new FragmentAdapter(getSupportFragmentManager(),fragments);
        //vp_fragment.setAdapter(adapter);
        vp_fragment.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                Log.e(TAG, "onItemSelected: "+ position);
            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });*/
    }

    /**
     * 初始化菜单
     * 菜单源于{@link:https://gitee.com/mirrors/JpSpringMenu}
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initMenu() {
        //侧边栏菜单
        initSpringMenu();
        initMenuTitleBar();
        addMenuAdapter();
        //底部菜单
        initBottomMenu();
    }

    /**
     * 底部菜单
     */
    @SuppressLint("ClickableViewAccessibility")
    private void initBottomMenu() {
        mainFragment = findViewById(R.id.main_fragment);
        bottomView = findViewById(R.id.B_Menu_Layout);
        bottomView.setMenu(R.menu.bottom_menu);
        bottomView.setMsgCount(0, -30);
        bottomView.setMsgCount(1, 20);
        bottomView.setMsgCount(3, 300);
        bottomView.setFloatingEnable(true);

        FragmentSetting fragmentSetting = new FragmentSetting();
        Fragmentone fragmentone = new Fragmentone();
        FragmentTwo fragmentTwo = new FragmentTwo();
        FragmentThree fragmentThree = new FragmentThree();
        FragmentFour fragmentFour = new FragmentFour();
        bottomView.setFragmentManager(getSupportFragmentManager(), mainFragment);

        Bundle bundle = new Bundle();
        bundle.putSerializable("user", user);//传序列化的对象
        fragmentSetting.setArguments(bundle);

        bottomView.addFragment(R.id.tab1, fragmentone);
        bottomView.addFragment(R.id.tab2, fragmentTwo);
        bottomView.addFragment(R.id.tab3, fragmentThree);
        bottomView.addFragment(R.id.tab4, fragmentSetting);
        bottomView.addFragment(R.id.tab5, fragmentFour);
        bottomView.setOnItemSelectedListener(new BottomNavigationBar.OnItemSelectedListener() {
            @Override
            public void onItemSelected(BottomNavigationBar.Item item, int position) {
                switch (position) {
                    case 0:
                        Log.e(TAG, "onItemSelected: 0");
                        break;
                    case 1:
                        Log.e(TAG, "onItemSelected: 1");
                        break;
                    case 2:
                        Log.e(TAG, "onItemSelected: 2");
                        break;
                    case 3:
                        Log.e(TAG, "onItemSelected: 3");
                        break;
                    case 4:
                        Log.e(TAG, "onItemSelected: 4");
                        break;

                }

            }
        });

        /*//给菜单添加滑动监听
        mGestureDetector=new GestureDetector(this,new LearnGestureListener());
        bottomView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return mGestureDetector.onTouchEvent(motionEvent);
            }
        });*/
        //bottomView.addFragment(R.id.tab1,new oneFragment());
    }

    private void initSpringMenu() {
        mSpringMenu = new SpringMenu(this, R.layout.view_menu);
        mSpringMenu.setAlpha((float) 0.6); //设置背景透明度
        mSpringMenu.setMenuListener(this);
        mSpringMenu.setFadeEnable(true);
        // mSpringMenu.setChildSpringConfig(SpringConfig.fromOrigamiTensionAndFriction(20, 5));
        mSpringMenu.setDragOffset(0.4f);
        img_icon = mSpringMenu.findViewById(R.id.img_icon);
        img_icon.setOnLongClickListener(iconLongListener);
        //img_icon.setImageBitmap(mBitmap);

        //mSpringMenu.addIgnoredView();
    }

    private void initMenuTitleBar() {
        mTitleBar = findViewById(R.id.title_bar);
        //mTitleBar.setLeftText("Left");
        /*****************左边侧边栏**********************/
        mTitleBar.setLeftImageResource(R.drawable.menu);
        mTitleBar.setTitle(R.string.app_name);
        mTitleBar.setBackgroundColor(Color.parseColor("#c2d1ef"));
        mTitleBar.setDividerColor(Color.GRAY);
        mTitleBar.setTitleColor(Color.WHITE);
        //左边的按键监听
        mTitleBar.setLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSpringMenu.setDirection(SpringMenu.DIRECTION_LEFT);
                mSpringMenu.openMenu();
            }
        });

        /*****************右边侧边栏**********************/


    }

    private void addMenuAdapter() {
        MenuListBean[] listBeen = {new MenuListBean(R.mipmap.ic_launcher, "指纹识别"),
                new MenuListBean(R.mipmap.ic_launcher, "登陆界面"),
                new MenuListBean(R.mipmap.ic_launcher, "人脸识别"),
                new MenuListBean(R.mipmap.ic_launcher, "Rusume"),
                new MenuListBean(R.mipmap.ic_launcher, "Tools"),
                new MenuListBean(R.mipmap.ic_launcher, "About"),
                new MenuListBean(R.mipmap.ic_launcher, "静拍模式")};
        MyMenuAdapter adapter = new MyMenuAdapter(this, listBeen, listener);
        ListView listView = mSpringMenu.findViewById(R.id.lv_select);
        listView.setAdapter(adapter);

    }

    private boolean menustatus = false;

    /*******Menu******/
    @Override
    public void onMenuOpen() {
//        Toast.makeText(this, "Menu is opened!!", Toast.LENGTH_SHORT).show();
        wv_reusme.setVisibility(View.GONE);
        menustatus = true;
    }

    @Override
    public void onMenuClose() {
//        Toast.makeText(this, "Menu is close!!", Toast.LENGTH_SHORT).show();
        menustatus = false;
    }

    @Override
    public void onProgressUpdate(float value, boolean bouncing) {

    }
    /*******Menu******/

    /**
     * 头像长按监听
     * 功能：重新从图库选择图片
     */
    View.OnLongClickListener iconLongListener = new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            Log.e(TAG, "onLongClick: 111111111111111111");
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, ACTION_CHOOSE_IMAGE);
            return true;
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTION_CHOOSE_IMAGE) {
            if (data == null || data.getData() == null) {
                Toast.makeText(this, getString(R.string.getpic), Toast.LENGTH_SHORT).show();
                return;
            }
            try {
                mBitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
            if (mBitmap == null) {
                Toast.makeText(this, getString(R.string.getpicfail), Toast.LENGTH_SHORT).show();
            }
            img_icon.setImageBitmap(mBitmap);
            //存文件部分暂不处理，手机权限禁止
           /* //bitmap转byte数组
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            mBitmap.compress(Bitmap.CompressFormat.JPEG,100,baos);
            byte[] imgdata=baos.toByteArray();

            File tempfile=getTempImage();
            try {
                FileOutputStream fos=new FileOutputStream(tempfile);
                fos.write(imgdata);
                fos.close();

            }catch (IOException e){
                e.printStackTrace();
            }*/
            /*Glide.with(img_icon.getContext())
                    .load(mBitmap)
                    .into(img_icon);*/
        }
    }

    /**
     * 菜单中的每个item项监听
     */
    MyMenuAdapter.MenuItemListener listener = new MyMenuAdapter.MenuItemListener() {
        @Override
        public void onMenuItemClickListener(Context context, int position) {
            switch (position) {
                case 0:
                    Biometric();
                    break;
                case 1:
                    startActivity(new Intent(context, ActivityLogin.class));
                case 2:
                    //ArcFaceRecognition();
                    startActivity(new Intent(context, FaceAttrVideoPreviewActivity.class));
                    break;
                case 3:
                    loadResume();
                    break;
                case 6://静拍
                    statrtJingPai();
                    break;
            }
        }
    };

    //开启静拍服务
    private void statrtJingPai() {
//        _colorAnimation.reverse();
        readyToGo();
        Toast.makeText(this, R.string.alert_capture_ready, Toast.LENGTH_SHORT).show();
    }
//开启服务
    private void readyToGo() {
        if (_isReadToGo)
            return;

        if (_camera == null) {
            try {
                _camera = Camera.open(_currentCameraIndex);
            } catch (Exception e) {
                Toast.makeText(this, R.string.warning_camera_not_available, Toast.LENGTH_SHORT).show();
                _isReadToGo = false;
                return;
            }
        }

        setCameraParams();
        _cameraPreview = new CameraPreview(this, _camera);
        _previewContainer.addView(_cameraPreview);
        MainActivity.this.getContentResolver().registerContentObserver(android.provider.Settings.System.CONTENT_URI, true, _volumeChanged);
        MainActivity.this.startService(new Intent(this, BGMusicService.class));

        _isReadToGo = true;
    }
//释放服务  关闭静拍
    public void releaseService() {

        if (_isReadToGo == false)
            return;

        if (_camera != null) {
            _camera.stopPreview();
            _camera.release();
            _camera = null;
        }
        _previewContainer.removeView(_cameraPreview);
        MainActivity.this.getContentResolver().unregisterContentObserver(_volumeChanged);
        MainActivity.this.stopService(new Intent(this, BGMusicService.class));
        _isReadToGo = false;
    }

    private void setCameraParams() {
        Camera.Parameters parameters = _camera.getParameters();

        int cameraPictureRotation;

        if (_currentCameraIndex == _back_camera_index) {
            cameraPictureRotation = 90;
            //set preview to right orientation
            // _camera.setDisplayOrientation(90);
        } else {
            cameraPictureRotation = 270;
        }
        List<String> focusModesList = parameters.getSupportedFocusModes();

        //增加对聚焦模式的判断
        if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
        } else if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
        } else if (focusModesList.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
        }

        parameters.setRotation(cameraPictureRotation);
        _camera.setParameters(parameters);
    }

    /**
     * 人脸识别
     */
    private void ArcFaceRecognition() {
    }

    /**
     * 生物识别相关
     */
    private void Biometric() {
        mSpringMenu.closeMenu();
        Biometric biometric = new Biometric();
        biometric.showBiometricPrompt(this, callback);
    }

    /**
     * 生物识别(指纹、人脸)检测结果回调
     */
    Biometric.AuthenticationcallBack callback = new Biometric.AuthenticationcallBack() {
        @Override
        public void success() {
            Toast.makeText(MainActivity.this, "认证成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void fail() {
            Toast.makeText(MainActivity.this, "Authentication failed",
                    Toast.LENGTH_SHORT)
                    .show();
        }
    };

    /**
     * 加载简历
     */
    private void loadResume() {
        mSpringMenu.closeMenu();//关闭菜单
        wv_reusme.setVisibility(View.VISIBLE);
        WebSettings webSettings = wv_reusme.getSettings();
        // 让WebView能够执行javaScript
        webSettings.setJavaScriptEnabled(true);
        // 让JavaScript可以自动打开windows
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        // 设置缓存
        webSettings.setAppCacheEnabled(true);
        // 设置缓存模式,一共有四种模式
        webSettings.setCacheMode(webSettings.LOAD_CACHE_ELSE_NETWORK);
        // 支持缩放(适配到当前屏幕)
        webSettings.setSupportZoom(true);
        // 将图片调整到合适的大小
        webSettings.setUseWideViewPort(true);
        // 支持内容重新布局,一共有四种方式
        // 默认的是NARROW_COLUMNS
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        // 设置可以被显示的屏幕控制
        webSettings.setDisplayZoomControls(true);
        // 设置默认字体大小
        webSettings.setDefaultFontSize(12);
        //禁用浏览器加载
        wv_reusme.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return false;
            }
        });
        wv_reusme.loadUrl("https://zhaozhi_gang.gitee.io/resume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        wv_reusme.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁webview
        constraint_parent.removeView(wv_reusme);
        releaseService();
        wv_reusme.destroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && wv_reusme.canGoBack()) {
            wv_reusme.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 获取SDCard的目录路径
     *
     * @return
     */
    public static String getSDOrDataCardPath() {
        File sdcardDir = null;
        //判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        if (sdcardExist) {//sd卡
            sdcardDir = Environment.getExternalStorageDirectory();
        } else {//手机内存
            sdcardDir = Environment.getDataDirectory();
        }
        return sdcardDir.toString();
    }

    /**
     * 创建更换头像的时候临时存储文件
     *
     * @return
     */

    private String directoryPath;
    private String myfilePath;

    private File getTempImage() {
        if (directoryPath == null) {
            directoryPath = getSDOrDataCardPath() + "/apricots/";
            Log.e(TAG, "getTempImage: " + directoryPath);
        }
        myfilePath = directoryPath + "icon.jpg";
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        File file = new File(myfilePath);
        return file;
    }


    /*****************************菜单滑动的探测器**************************/
   /* private GestureDetector mGestureDetector;
    private int verticalMinistance = 100;
    private int minVelocity = 10;            //最小识别速度
    public class LearnGestureListener extends GestureDetector.SimpleOnGestureListener{
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if (e1.getX() - e2.getX() > verticalMinistance && Math.abs(velocityX) > minVelocity) {
                showToast("left");
            } else if (e2.getX() - e1.getX() > verticalMinistance && Math.abs(velocityX) > minVelocity) {
                showToast("right");
            } else if (e1.getY() - e2.getY() > verticalMinistance && Math.abs(velocityY) > minVelocity) {
                showToast("up");
            } else if (e2.getY() - e1.getY() > verticalMinistance && Math.abs(velocityY) > minVelocity) {
                showToast("down");
            }
            return false;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    }

    public void showToast(String text) {
        Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
    }*/

    @Override
    public Context GetContext() {
        return MainActivity.this;
    }

    @Override
    public void TakenPicture() {
        if (_isReadToGo)
            _camera.takePicture(null, null, pictureCallback);
        _isReadToGo = false;
    }

    @Override
    public void OnEnter() {

    }
}
